package com.example.jobseek;

import java.util.Vector;
import java.util.concurrent.ExecutionException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import com.example.jobseek.ListaInvitado.show;
import com.example.jobseek.ListaInvitado.toAdapter;
import com.google.gson.Gson;

import domain.TrabajoVO;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.SearchView;
import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class ListaEmpleos extends ActionBarActivity {
	TextView header;
	ArrayAdapter<TrabajoVO> adaptador;
	ListView list1;
	String datos;
	Bundle bundle;
	String datosLog;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_lista_empleos);
		
		bundle = this.getIntent().getExtras();
		if (bundle!= null){
			datosLog = bundle.getString("datosLog");
		}
		header = new TextView(getBaseContext());
		header.setText("Lista de Empleos");
		header.setTextColor(Color.BLACK);
		list1 = (ListView) findViewById(R.id.listView1);
		list1.addHeaderView(header);
		list1.setAdapter(adaptador);
		list1.setTextFilterEnabled(true);

		
		
		
		new toAdapter(ListaEmpleos.this).execute();

		list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long i) {
				String dato = (String) list1.getItemAtPosition(position)
						.toString();
				
				// Creamos el Intent
				try {
					datos = new show().execute(dato).get();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (ExecutionException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				Intent intent = new Intent(ListaEmpleos.this,
						DetalleEmpleo.class);

				Bundle b = new Bundle();
				b.putString("rut", datosLog);
				b.putString("datos", datos);
				b.putString("tipo", "user");
				intent.putExtras(b);
				startActivity(intent);

			}

		});
	}

	@SuppressLint("NewApi")
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.lista_empleos, menu);
		SearchManager sm = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();

		searchView.setSearchableInfo(sm.getSearchableInfo(getComponentName()));
		//searchView.setIconifiedByDefault(false);

		SearchView.OnQueryTextListener textChangeListener = new SearchView.OnQueryTextListener() {
			@Override
			public boolean onQueryTextChange(String newText) {
				// this is your adapter that will be filtered
				adaptador.getFilter().filter(newText);
				System.out.println("on text chnge text: " + newText);
				return true;
			}

			@Override
			public boolean onQueryTextSubmit(String query) {
				// this is your adapter that will be filtered
				adaptador.getFilter().filter(query);
				System.out.println("on query submit: " + query);
				return true;
			}
		};
		searchView.setOnQueryTextListener(textChangeListener);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		super.onOptionsItemSelected(item);
		switch (item.getItemId()) {

		case R.id.advance:
			Intent i1 = new Intent(ListaEmpleos.this, BusquedaAvanzada.class);
			startActivity(i1);
			break;
		case R.id.profile:
			Bundle bundle = new Bundle();
			bundle.putString("rut", datosLog);
			Intent i2 = new Intent(ListaEmpleos.this, Perfil.class);
			i2.putExtras(bundle);
			startActivity(i2);
			break;
		case R.id.logout:
			Intent i3 = new Intent(ListaEmpleos.this, Principal.class);
			startActivity(i3);
			break;

		}
		return true;
	}

	class show extends AsyncTask<String, Void, String> {
		private static final String TAG = "listar";

		@Override
		protected String doInBackground(String... params) {
			String nombre = params[0];
			String result = "";

			try {

				result = obtenerDatosTrabajo(new TrabajoVO(nombre));

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			return result;
		}

	}

	class toAdapter extends AsyncTask<String, Void, ArrayAdapter<TrabajoVO>> {
		Context context;

		public toAdapter(Context context) {
			this.context = context;
		}

		private static final String TAG = "listar Trabajos";
		ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			progressDialog = ProgressDialog.show(ListaEmpleos.this,
					"Cargando...", "Por favor, espere", true, true);

		}

		@Override
		protected ArrayAdapter<TrabajoVO> doInBackground(String... params) {
			// TODO Auto-generated method stub
			String result = "";

			try {

				result = listarTrabajos();

			} catch (Exception e) {
				Log.e(TAG, e.getCause().toString());
			}

			TrabajoVO[] trabajos = new TrabajoVO[1];

			trabajos = (TrabajoVO[]) new Gson().fromJson(result,
					TrabajoVO[].class);

			adaptador = new ArrayAdapter<TrabajoVO>(context, android.R.layout.simple_list_item_1, trabajos);
			return adaptador;
		}

		@Override
		protected void onPostExecute(ArrayAdapter<TrabajoVO> result) {
			super.onPostExecute(result);
			progressDialog.dismiss();

			list1.setAdapter(result);

		}

	}

	public String listarTrabajos() {
		String result = "";

		String method = "listarTrabajos";
		String TAG = method;
		Log.i("intentando enviar datos al ws usando: ", method);

		try {
			String SOAP_ACTION = util.Constantes.NAMESPACE + "#" + method;

			SoapObject request = new SoapObject(util.Constantes.NAMESPACE,
					method);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER12);

			envelope.setOutputSoapObject(request);

			envelope.addMapping(util.Constantes.NAMESPACE, "TrabajoVO",
					new TrabajoVO().getClass());

			HttpTransportSE transporte = new HttpTransportSE(
					util.Constantes.URL);
			transporte.debug = true;

			transporte.call(SOAP_ACTION, envelope);

			Log.i(TAG, "dump Request: " + transporte.requestDump);
			Log.i(TAG, "dump Response: " + transporte.responseDump);

			Vector response = (Vector) envelope.getResponse();
			result = (String)response.get(1);
			return result;

		} catch (Exception e) {
			e.printStackTrace();

		}

		return null;

	}

	public String obtenerDatosTrabajo(TrabajoVO oTrabajoVO) {
		String result = "";

		String method = "getDatosTrabajo";
		String TAG = method;
		Log.i("intentando enviar datos al ws usando: ", method);

		try {
			String SOAP_ACTION = util.Constantes.NAMESPACE + "#" + method;

			SoapObject request = new SoapObject(util.Constantes.NAMESPACE,
					method);

			Gson gson = new Gson();
			String trabajo = gson.toJson(oTrabajoVO);

			request.addProperty("json", trabajo);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER12);

			envelope.setOutputSoapObject(request);

			envelope.addMapping(util.Constantes.NAMESPACE, "TrabajoVO",
					new TrabajoVO().getClass());

			HttpTransportSE transporte = new HttpTransportSE(
					util.Constantes.URL);
			transporte.debug = true;

			transporte.call(SOAP_ACTION, envelope);

			Log.i(TAG, "dump Request: " + transporte.requestDump);
			Log.i(TAG, "dump Response: " + transporte.responseDump);

			Vector response = (Vector) envelope.getResponse();
			result = (String)response.get(1);
			return result;

		} catch (Exception e) {
			e.printStackTrace();

		}

		return null;

	}
}
